const {ccclass, property} = cc._decorator;
// import {Buffer} from '../../../__node_modules/buffer';

@ccclass
export default class History extends cc.Component{

    /**
     * 历史记录总节点
     */
    history: cc.Node;

    viewList: cc.Node;
    content: cc.Node;
    viewitemTemp: cc.Node;
    historyData: cc.history[];
    curRoomInfo: cc.history;

    /**暂无战绩的节点 */
    emptyTip: cc.Node;
    onLoad(){

        this.history = this.node.getChildByName('history');
        this.history.active = false;

        this.emptyTip = this.history.getChildByName('emptyTip');
        this.emptyTip.active = true;

        this.viewList = this.history.getChildByName('viewlist');
        this.content = cc.find('view/content', this.viewList);

        this.viewitemTemp = this.content.children[0];
        this.content.removeChild(this.viewitemTemp);

        const btn_zhanji = cc.find('Canvas/btn_zhanji');
        cc.vv.utils.addClickEvent(btn_zhanji, this.node, 'History', 'onBtnHistoryClicked');

        const btn_back = cc.find('Canvas/history/btn_back');
        cc.vv.utils.addClickEvent(btn_back, this.node, 'History', 'onBtnBackClicked');
    }

    onBtnOpClicked(event: cc.Event){
        const idx = event.target.parent.idx;
        if(this.curRoomInfo == null){
            this.getGameListOfRoom(idx);
        }
        else{      
            this.getDetailOfGame(idx);
        }
    }


    onViewItemClicked(event: cc.Event){
        const idx = event.target.idx;
        if(this.curRoomInfo == null){
            this.getGameListOfRoom(idx);
        }
        else{
            this.getDetailOfGame(idx);
        }
    }


    getDetailOfGame(idx){
        const roomUUID = this.curRoomInfo.uuid;
        cc.vv.userMgr.getDetailOfGame(roomUUID, idx, (data) => {
            data.base_info = JSON.parse(<string>data.base_info);
            data.action_records = JSON.parse(data.action_records);
            cc.vv.gameNetMgr.prepareReplay(this.curRoomInfo, data);
            cc.vv.replayMgr.init(data);
            cc.director.loadScene('mjgame');
        });
    }


    getGameListOfRoom(idx: number){
        const roomInfo = this.historyData[idx];
        cc.vv.userMgr.getGamesOfRoom(roomInfo.uuid, (data) => {
            if(data != null && data.length > 0){
                
            }
        });
    }

    initGameHistoryList(roomInfo: cc.history, data: cc.roomInfo[]){
        data.sort((a, b) => {
            return a.create_time - b.create_time;
        });

        data.map((item, i) => {
            const node = this.getViewItem(i);
            const idx = data.length - i - 1;
            node['idx'] = idx;
            const titleId = (idx + 1) + '';
            node.getChildByName('title').getComponent(cc.Label).string = titleId;
            node.getChildByName('roomNo').getComponent(cc.Label).string = '房间ID：' + roomInfo.id;
            node.getChildByName('time').getComponent(cc.Label).string = this.dateFormat(item.create_time * 1000);

            const btnOp = node.getChildByName('btnOp');
            btnOp['idx'] = idx;
            btnOp.getChildByName('Label').getComponent(cc.Label).string = '回放';

            const result = JSON.parse(item.result);
            for(let j = 0; j < 4; j++){
                let s = roomInfo.seats[j];
                let info = s.name + ':' + result[j];
                node.getChildByName('info' + j).getComponent(cc.Label).string = info;
            }
        });
        this.shrinkContent(data.length);
        this.curRoomInfo = roomInfo;
    }


    onBtnBackClicked(){
        if(this.curRoomInfo == null){
            this.historyData = null;
            this.history.active = false;
        }
        else{
            this.initRoomHistoryList(this.historyData);
        }
    }

    onBtnHistoryClicked(){
        this.history.active = true;
        cc.vv.userMgr.getHistoryList((data) => {
            data.sort((a, b) => {
                return a.time - b.time;
            });
            this.historyData = data;
            this.historyData.map((history) => {
                for(let i = 0; i < 4; i++){
                    let s = history.seats[i];
                    // s.name = new Buffer(s.name, 'base64').toString();
                } 
            });
            this.initRoomHistoryList(this.historyData);
        });
    }


    initRoomHistoryList(data: cc.history[]){
        data.map((history, i) => {
            const node = this.getViewItem(i);
            node['idx'] = i;
            const titleId = i + 1 + '';
            node.getChildByName('title').getComponent(cc.Label).string = titleId;
            node.getChildByName('roomNo').getComponent(cc.Label).string = '房间ID：' + history.id;
            const datatime = this.dateFormat(history.time * 1000);
            node.getChildByName('time').getComponent(cc.Label).string = datatime;

            const btnOp = node.getChildByName('btnOp');
            btnOp['idx'] = i;
            btnOp.getChildByName('Label').getComponent(cc.Label).string = '详情';

            for(let j = 0; i < 4; j++){
                let s = history.seats[j];
                let info = s.name + ':' + s.score;
                node.getChildByName('info' + j).getComponent(cc.Label).string = info;
            }
        });

        this.emptyTip.active = data.length == 0;
        this.shrinkContent(data.length);
        this.curRoomInfo = null;
    }

    shrinkContent(num: number){
        while(this.content.childrenCount > num){
            let lastOne = this.content.children[this.content.childrenCount - 1];
            this.content.removeChild(lastOne);
        }
    }

    dateFormat(time){
        const date = new Date(time);
        let datetime = '{0}-{1}-{2} {3}:{4}:{6}';

        const year = date.getFullYear();
        const newborn_month = date.getMonth() + 1;
        const newborn_day = date.getDate();
        const newborn_h = date.getHours();
        const newborn_m = date.getMinutes();
        const newborn_s = date.getSeconds();

        const month = newborn_month >= 10 ? newborn_month : '0' + newborn_month;
        const day = newborn_day >= 10 ? newborn_day : '0' + newborn_day;
        const h = newborn_h >= 10 ? newborn_h : '0' + newborn_h;
        const m = newborn_m >= 10 ? newborn_m : '0' + newborn_m;
        const s = newborn_s >= 10 ? newborn_s : '0' + newborn_s;

        datetime = datetime.format(year, month, day, h, m, s);
        return datetime;
    }


    getViewItem(index: number){
        const content = this.content;
        if(content.childrenCount > index){
            return content.children[index];
        }

        const node = cc.instantiate(this.viewitemTemp);
        content.addChild(node);
        return node;
    }
}